﻿using Common;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AI.Steering
{
    /// <summary>
    /// 运动体
    /// </summary>
    public class Locomotion : MonoBehaviour
    {
        [Tooltip("计算合力间隔")]
        public float calculateFinalInterval = 0.1f;

        public Vector3 currentForce;

        private Vector3 finalForce;

        [Tooltip("质量")]
        public float mass = 1;

        [Tooltip("最大移动速度")]
        public float maxMoveSpeed = 10;

        public float rotateSpeed = 50;

        [Tooltip("是否在平面运动")]
        public bool isPlane;

        private Steering[] steerings;

        private void CalculateFinalForce()
        {
            finalForce = Vector3.zero;
            for (int i = 0; i < steerings.Length; i++)
            {
                //累加所有操控的实际力
                finalForce += steerings[i].GetForce();
            }
            finalForce /= steerings.Length;
            //如果合力为零，则当前力为零
            if (finalForce == Vector3.zero)
            {
                currentForce = Vector3.zero;
            }
            //考虑当前运动体质量（质量大、力度小）
            finalForce /= mass;
            //如果仅仅在平面运动，则合力高度为零
            if (isPlane)
            {
                currentForce.y = 0;
            }
        }

        private void Start()
        {
            //获取所有操控
            steerings = GetComponents<Steering>();
            InvokeRepeating("CalculateFinalForce", 0, calculateFinalInterval);
        }

        private void Update()
        {
            //移动
            Movement();
            //旋转
            TransformHelper.LookDirection(transform,currentForce,rotateSpeed);
        }
        protected virtual void Movement()
        {
            //CalculateFinalForce();//放在协程中做，不建议每帧做
            //将合力叠加到当前操控力上
            currentForce += finalForce * Time.deltaTime;//累加合力 以秒为单位
            //限制最大速度
            currentForce = Vector3.ClampMagnitude(currentForce, maxMoveSpeed);
        }
    }
}